package com.base.component.ai.workflow.handle;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.base.component.ai.agent.bo.ContextBO;
import com.base.component.ai.agent.bo.ContextParamBO;
import com.base.component.ai.workflow.core.NodeHandle;
import com.base.component.ai.workflow.flow.Flow;
import com.base.component.ai.workflow.logs.NodeLog;
import com.base.component.ai.workflow.logs.NodeLogVariable;
import com.base.component.ai.workflow.node.Node;
import com.base.component.ai.workflow.node.NodeVariable;
import com.base.component.ai.workflow.utils.FlowUtils;
import com.greenpineyu.fel.FelEngine;
import com.greenpineyu.fel.FelEngineImpl;
import com.greenpineyu.fel.context.FelContext;

@Component
public class NodeHandleVariable<MSG,AP extends ContextParamBO,PP> implements NodeHandle<MSG,AP,PP>{

	@Override
	public <T extends Node> boolean support(Class<T> cls) {
		return cls.equals( NodeVariable.class);
	}

	@Override
	public <T extends Node>List<Flow> execute(ContextBO<MSG,AP,PP> context,Map<String,Object> params,Flow flow,T node,Consumer<NodeLog> c) {
		NodeVariable d=(NodeVariable)node;
		Map<String,Object> expressionMap=new HashMap<>();
		if(!CollectionUtils.isEmpty(d.getVarExpression())) {
			FelEngine felEngine = new FelEngineImpl();
			FelContext felContext = felEngine.getContext();
			for(String key:params.keySet()) {
				felContext.set(key,params.get(key));
			}
			for(String variable:d.getVarExpression().keySet()) {
				String expression=d.getVarExpression().get(variable);
				expressionMap.put(variable, felEngine.eval(expression, felContext));
			}
		}
		Map<String,Object> varMap=FlowUtils.paramConverMap(expressionMap, d.getVarValue());
		if(!CollectionUtils.isEmpty(varMap)) {
			params.putAll(varMap);
		}
		NodeLogVariable nodeLog=new NodeLogVariable();
		nodeLog.setVarMap(varMap);
		c.accept(nodeLog);
		return flow.getNexts();
	}
	
}
